﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace WorkStation.Frameworks.Core.Extensions
{
    /// <summary>
    /// 字节数组扩展
    /// </summary>
    public static class BytesExtensions
    {
        /// <summary>
        /// 从字节数组转换为字符串 编码：ASCII
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToStringByASCII(this byte[] input) 
        {
            return Encoding.ASCII.GetString(input);
        }

        /// <summary>
        /// 从字节数组转换为字符串 编码：UTF8
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToStringByUTF8(this byte[] input) 
        {
            return Encoding.UTF8.GetString(input);
        }

        /// <summary>
        /// 将字节数组转化为对象
        /// </summary>
        /// <typeparam name="T">目标对象类型</typeparam>
        /// <param name="input"></param>
        /// <returns></returns>
        public static T GetObject<T>(this byte[] input) 
        {
            using (MemoryStream stream = new MemoryStream())
            {
                try
                {
                    stream.Write(input, 0, input.Length);

                    BinaryFormatter formatter = new BinaryFormatter();

                    stream.Seek(0, SeekOrigin.Begin);

                    T res = (T)formatter.Deserialize(stream);

                    return res;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                        stream.Dispose();
                    }
                }
            }
        }
    }
}
